﻿using Microsoft.SharePoint;

namespace Eneta.Portal.Authentication.Live
{
    class SettingsFeatureReceiver : SPFeatureReceiver
    {
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;

            using (SPSite lSite = new SPSite(AuthConfig.ProfileSiteUrl))
            {
                using (SPWeb lWeb = lSite.OpenWeb())
                {
                    SPList lList = lWeb.Lists["LiveProfileSync"];
                    SPListItem item = lList.Items.Add();
                    item["Url"] = site.Url;
                    item["Title"] = site.Url;
                    item.Update();
                }
            }
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;

            using (SPSite lSite = new SPSite(AuthConfig.ProfileSiteUrl))
            {
                using (SPWeb lWeb = lSite.OpenWeb())
                {
                    SPList lList = lWeb.Lists["LiveProfileSync"];
                    SPQuery query = new SPQuery();
                    query.Query = string.Format("<Where><Eq><FieldRef Name='Url'/><Value Type='Text'>{0}</Value></Eq></Where>", site.Url);
                    SPListItemCollection items = lList.GetItems(query);

                    if (items.Count > 0)
                    {
                        items[0].Delete();
                    }

                    lList.Update();
                }
            }
        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
        }
    }
}
